<?php

namespace addons\zzuser\controller\api;

use addons\zzuser\model\UserM;
use app\common\controller\Api;
use Faker\Factory;
use fast\Http;
use think\Env;
use think\Validate;

class LoginByWechatCode extends Api
{
    protected $noNeedLogin = 'index';

    public function index()
    {
        $validate = new Validate();
        if (!$validate->check(input(), [
            'code'      => 'require',
            'rawData'   => 'require',
            'signature' => 'require'
        ])) {
            $this->error($validate->getError());
        }
        $code      = input('code');
        $rawData   = input('rawData');
        $signature = input('signature');

        $app_id     = Env::get('wechat.miniapp_id');
        $app_secret = Env::get('wechat.miniapp_secret');

        $openid_and_session_key = Http::get("https://api.weixin.qq.com/sns/jscode2session?appid=$app_id&secret=$app_secret&js_code=$code&grant_type=authorization_code");
        $openid_and_session_key = json_decode($openid_and_session_key, true);
        if (!isset($openid_and_session_key['openid']) || !isset($openid_and_session_key['session_key'])) {
            $this->error('error openid_and_session_key');
        }

        $userinfo = htmlspecialchars_decode($rawData);
        if (sha1($userinfo . $openid_and_session_key['session_key']) != $signature) {
            $this->error('error signature');
        }
        $userinfo = json_decode($userinfo, true);
        $user     = UserM::where('openid', $openid_and_session_key['openid'])->find();
        if (!$user) {
            $faker = Factory::create();
            $user  = UserM::create([
                'status'   => UserM::STATUS_NORMAL,
                'openid'   => $openid_and_session_key['openid'],
                'nickname' => $faker->name,
                'jointime' => time(),
                'avatar'   => $userinfo['avatarUrl'],
                'gender'   => $userinfo['gender'],
                'joinip'   => request()->ip()
            ]);
        }
        $this->auth->direct($user['id']);
        $this->success('', [
            'token ' => $this->auth->getToken(),
        ]);
    }
}
